package com.gogowan.agroenterprise.widget.wheel;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import com.gogowan.agroenterprise.R;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;

/**
 * 行业两级联动界面
 * 
 * @author Administrator
 *
 */
public class VocationWheelActivity extends Activity implements OnClickListener,
		OnWheelChangedListener {
	private WheelView vocation1;
	private WheelView vocation2;
	private Button mBtnConfirm;
	private Button mBtnCancel;

	private ArrayList<TradeInfo> vocationAL = new ArrayList<TradeInfo>();
	private HashMap<String, String> hm = new HashMap<String, String>();
	private boolean flag = false;
	private ArrayList<String> al = new ArrayList<String>();

	/**
	 * 所有一级行业
	 */
	protected String[] mVocationDatas;
	/**
	 * key - 一级行业 value - 二级行业
	 */
	protected Map<String, String[]> mVocationDatasMap = new HashMap<String, String[]>();

	/**
	 * 当前一级行业的名称
	 */
	protected String mCurrentVocation1Name;
	/**
	 * 当前二级行业的名称
	 */
	protected String mCurrentVocation2Name;

	/**
	 * 解析省市区的数据
	 */

	protected void initVocationDatas() {
		AssetManager asset = getAssets();
		try {
			InputStream input = asset.open("vocation_data.xml");
			// 创建一个解析xml的工厂对象
			SAXParserFactory spf = SAXParserFactory.newInstance();
			// 解析xml
			SAXParser parser = spf.newSAXParser();
			XmlParserHandler2 handler = new XmlParserHandler2();
			parser.parse(input, handler);
			input.close();
			// 获取解析出来的数据
			vocationAL = handler.getDataList();

			// */
			mVocationDatas = new String[vocationAL.size()];
			for (int i = 0; i < vocationAL.size(); i++) {
				// 遍历所有省的数据
				hm.put(vocationAL.get(i).getTradeName(), vocationAL.get(i)
						.getTradeCode());// 将一级行业信息放入hashmap
				mVocationDatas[i] = vocationAL.get(i).getTradeName();
				List<TradeInfo> twoList = vocationAL.get(i).getChildList();
				String[] twoNames = new String[twoList.size()];
				for (int j = 0; j < twoList.size(); j++) {
					// 遍历省下面的所有市的数据
					hm.put(twoList.get(j).getTradeName(), twoList.get(j)
							.getTradeCode());// 将二级行业信息放入hashmap
					twoNames[j] = twoList.get(j).getTradeName();
				}
				// 省-市的数据，保存到mCitisDatasMap
				mVocationDatasMap.put(vocationAL.get(i).getTradeName(),
						twoNames);
			}
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {

		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.wheel_vocation_activity);

		VocationWheelActivity.this.overridePendingTransition(R.anim.bottom_in,
				R.anim.bottom_out);

		// WindowManager m = getWindowManager();
		// Display d = m.getDefaultDisplay(); // 为获取屏幕宽、高

		LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值
		getWindow().setGravity(Gravity.LEFT | Gravity.BOTTOM);
		p.x = 0; // 新位置X坐标
		p.y = 0; // 新位置Y坐标
		// p.height = (int) (d.getHeight() * 0.3); // 高度设置为屏幕的1.0
		// p.width = (int) (d.getWidth() - 40); // 宽度设置为屏幕的0.8
		// p.alpha = 1.0f; // 设置本身透明度
		// p.dimAmount = 1.5f; //设置黑暗度

		getWindow().setAttributes(p); // 设置生效

		setUpViews();
		setUpListener();
		setUpData();

		flag = true;
	}

	private void setUpViews() {
		vocation1 = (WheelView) findViewById(R.id.vocation1);
		vocation2 = (WheelView) findViewById(R.id.vocation2);
		mBtnConfirm = (Button) findViewById(R.id.btn_confirm2);
		mBtnCancel = (Button) findViewById(R.id.btn_cancel2);
	}

	private void setUpListener() {
		// 添加change事件
		vocation1.addChangingListener(this);
		// 添加change事件
		vocation2.addChangingListener(this);
		// 添加onclick事件
		mBtnConfirm.setOnClickListener(this);
		// 添加onclick事件
		mBtnCancel.setOnClickListener(this);
	}

	private void setUpData() {
		initVocationDatas();
		vocation1.setViewAdapter(new ArrayWheelAdapter<String>(
				VocationWheelActivity.this, mVocationDatas));
		al = getIntent().getStringArrayListExtra("vocationContent");
		// 设置可见条目数量
		vocation1.setVisibleItems(7);
		vocation2.setVisibleItems(7);
		if (al != null && al.size() > 0)
			vocation1.setCurrentItem(Integer.parseInt(al.get(4)));
		updateCities();
	}

	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		if (flag) {
			if (wheel == vocation1) {
				updateCities();
			} else if (wheel == vocation2) {
				updateAreas();
			}
		}
	}

	/**
	 * 根据当前的市，更新区WheelView的信息
	 */
	private void updateAreas() {
		int pCurrent = vocation2.getCurrentItem();
		mCurrentVocation2Name = mVocationDatasMap.get(mCurrentVocation1Name)[pCurrent];

	}

	/**
	 * 根据当前的省，更新市WheelView的信息
	 */
	private void updateCities() {
		int pCurrent = vocation1.getCurrentItem();
		mCurrentVocation1Name = mVocationDatas[pCurrent];
		String[] cities = mVocationDatasMap.get(mCurrentVocation1Name);
		if (cities == null) {
			cities = new String[] { "" };
		}
		vocation2.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));

		if (flag == false && al != null && al.size() > 0) {
			vocation2.setCurrentItem(Integer.parseInt(al.get(5)));
			mCurrentVocation2Name = al.get(2);
		} else {
			vocation2.setCurrentItem(0);
			mCurrentVocation2Name = cities[0];
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_confirm2:
			showSelectedResult();
			break;
		case R.id.btn_cancel2:
			VocationWheelActivity.this.finish();
			VocationWheelActivity.this.overridePendingTransition(
					R.anim.bottom_out1, R.anim.bottom_in1);
			break;
		}
	}

	private void showSelectedResult() {
		// Toast.makeText(VocationWheelActivity.this,
		// "当前选中:" + mCurrentVocation1Name + "," + mCurrentVocation2Name,
		// Toast.LENGTH_SHORT).show();
		ArrayList<String> al2 = new ArrayList<String>();
		al2.add(mCurrentVocation1Name);
		al2.add(hm.get(mCurrentVocation1Name));
		al2.add(mCurrentVocation2Name);
		al2.add(hm.get(mCurrentVocation2Name));
		al2.add(vocation1.getCurrentItem() + "");
		al2.add(vocation2.getCurrentItem() + "");
//		Intent aintent = new Intent(VocationWheelActivity.this,
//				RegisterActivity.class);
		Intent aintent = new Intent();
		aintent.putStringArrayListExtra("vocation", al2);
		setResult(RESULT_OK, aintent);

		VocationWheelActivity.this.finish();
		VocationWheelActivity.this.overridePendingTransition(
				R.anim.bottom_out1, R.anim.bottom_in1);

	}

	/**
	 * 返回
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK)// 返回键
		{
			VocationWheelActivity.this.finish();
			VocationWheelActivity.this.overridePendingTransition(
					R.anim.bottom_out1, R.anim.bottom_in1);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	// 点击空白处消失
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		VocationWheelActivity.this.finish();
		VocationWheelActivity.this.overridePendingTransition(
				R.anim.bottom_out1, R.anim.bottom_in1);
		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (vocationAL != null) {
			vocationAL.clear();
			vocationAL = null;
		}
		if (hm != null) {
			hm.clear();
			hm = null;
		}
		if (mVocationDatas != null) {
			mVocationDatas = null;
		}
		if (mVocationDatasMap != null) {
			mVocationDatasMap.clear();
			mVocationDatasMap = null;
		}
	}
}
